<template>
	<div>
		<Content>
			<Form :label-width="140" class="form-css">
				<h1>
					<span>基本信息</span>
				</h1>
				<FormItem label="旅居商品名称" required>
					<Input class="view-input" v-model="formData.spuName" placeholder="请输入商品名称" />
				</FormItem>
				<FormItem label="商品分类" required>
					<Cascader class="view-input" :data="categoryList" v-model="categoryArray" :load-data="loadData"></Cascader>
				</FormItem>
				<FormItem label="客房编号" required>
					<Input class="view-input" :max="24" placeholder="不同客房的编号保持唯一" v-model="formData.sojournEntity.roomNumber" />
				</FormItem>
				<!-- <FormItem label="预订模式" required>
					<RadioGroup v-model.number="formData.sojournEntity.bookingMode">
						<Radio :label="0">
							<span>日租模式</span>
						</Radio>
						<Radio :label="1">
							<span>长租模式</span>
						</Radio>
						<Radio :label="2">
							<span>套餐模式</span>
						</Radio>
					</RadioGroup>
				</FormItem> -->
				<!-- <FormItem label="联系方式" v-if="formData.sojournEntity.bookingMode===1" required>
					<Input class="view-input" :max="64" placeholder="请输入客房联系电话" v-model="formData.sojournEntity.contactMobile" />
				</FormItem>
				<FormItem label="套餐天数(晚)" v-if="formData.sojournEntity.bookingMode===2" required>
					<InputNumber :min="1" placeholder="请输入套餐天数(晚)" v-model="formData.sojournEntity.taocanDay" />
				</FormItem> -->
				<FormItem label="供应商" required>
					<Select class="view-input" placeholder="请选择供应商" v-model="formData.orgId" :disabled="orgFreeze">
						<Option v-for="item in seletions" :value="item.orgId" :key="item.orgId">{{item.orgName}}</Option>
					</Select>
				</FormItem>
				<FormItem label="商品标签">
					<Input class="view-input" :max="64" placeholder="多个标签请用空格分隔，如：优选 特惠 新品" v-model="formData.viewLabel" />
				</FormItem>
				<FormItem label="房型介绍">
					<Input class="view-input" :max="128" placeholder="请输入房型信息" v-model="formData.sojournEntity.roomType" />
				</FormItem>
				<FormItem label="店铺商品分类">
					<Select class="view-input" placeholder="请选择店铺商品分类" v-model="formData.shopCategoryId">
						<Option v-for="item in shopCategoryList" :value="item.shopCategoryId" :key="item.shopCategoryId">{{item.categoryName}}</Option>
					</Select>
				</FormItem>
				<FormItem label="商品图" required>
					<template>
						<div class="demo-upload-list" v-for="(item,id) in spuUploadList" :key="id">
							<template v-if="item.status === 'finished'">
								<img :src="item.src" alt="img">
								<div class="demo-upload-list-cover">
									<Icon type="ios-eye-outline" @click.native="handleView(item.src)" title="预览"></Icon>
									<Icon type="ios-trash-outline" @click.native="handleRemove(id)" title="删除"></Icon>
								</div>
							</template>
							<template v-else>
								<Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
							</template>
						</div>
						<Upload ref="spu_upload"
							:show-upload-list="false"
							:on-success="onUploadSuccess"
							:format="['jpg','jpeg','png']"
							:max-size="4096"
							:on-format-error="handleFormatError"
							:on-exceeded-size="handleMaxSize"
							:before-upload="spuHandleBeforeUpload"
							type="drag"
							name="binaryFile"
							:headers="uploadHeader"
							:data="uploadParam"
							:action="uploadApi"
							style="display: inline-block;width:58px;">
							<div style="width: 58px;height:58px;line-height: 58px;">
								<Icon type="ios-camera" size="20"></Icon>
							</div>
						</Upload>
						<span style="font-size:12px;color:gray;margin-left:5px;position:relative;top:-10px">最多支持5张图片，图片尺寸建议800×800像素</span>
					</template>
				</FormItem>
				<FormItem label="详情地址">
					<Input class="view-input" :max="64" placeholder="请输入商品详细地区" v-model="formData.productionPlace" />
				</FormItem>
				<FormItem label="经度坐标(GCJ02)">
					<Input class="view-input" :max="64" placeholder="请输入经度坐标(GCJ02坐标系)" v-model="formData.gpsLongitude" />
				</FormItem>
				<FormItem label="纬度坐标(GCJ02)">
					<Input class="view-input" :max="64" placeholder="请输入纬度坐标(GCJ02坐标系)" v-model="formData.gpsLatitude" />
				</FormItem>

				<div class="sojourn-goods">
					<FormItem label="基础设施">
						<CheckboxGroup v-model="basicLabels">
							<Checkbox label="无线网络"></Checkbox>
							<Checkbox label="挂式空调"></Checkbox>
							<Checkbox label="晾衣架"></Checkbox>
							<Checkbox label="免费瓶装水"></Checkbox>
							<Checkbox label="低楼层无电梯"></Checkbox>
							<Checkbox label="窗户"></Checkbox>
							<Checkbox label="电视"></Checkbox>
							<Checkbox label="冰箱"></Checkbox>
							<Checkbox label="洗衣机"></Checkbox>
							<Checkbox label="投影"></Checkbox>
							<Checkbox label="电梯"></Checkbox>
							<Checkbox label="中央空调"></Checkbox>
						</CheckboxGroup>
					</FormItem>
					<FormItem label="服务内容">
						<CheckboxGroup v-model="serviceLabels">
							<Checkbox label="免费停车位"></Checkbox>
							<Checkbox label="行李寄存"></Checkbox>
							<Checkbox label="前台服务"></Checkbox>
						</CheckboxGroup>
					</FormItem>
					<FormItem label="卫浴标签">
						<CheckboxGroup v-model="bathroomLabels">
							<Checkbox label="热水"></Checkbox>
							<Checkbox label="独立卫浴"></Checkbox>
							<Checkbox label="电吹风"></Checkbox>
							<Checkbox label="洗浴用品"></Checkbox>
							<Checkbox label="牙具"></Checkbox>
							<Checkbox label="浴巾"></Checkbox>
							<Checkbox label="毛巾"></Checkbox>
							<Checkbox label="干湿分离"></Checkbox>
							<Checkbox label="免费洗衣服"></Checkbox>
						</CheckboxGroup>
					</FormItem>
					<FormItem label="位置周边">
						<CheckboxGroup v-model="locationArounds">
							<Checkbox label="超市"></Checkbox>
							<Checkbox label="地铁"></Checkbox>
							<Checkbox label="便利店"></Checkbox>
							<Checkbox label="餐厅"></Checkbox>
							<Checkbox label="药店"></Checkbox>
							<Checkbox label="公园"></Checkbox>
							<Checkbox label="菜市场"></Checkbox>
							<Checkbox label="提款机"></Checkbox>
						</CheckboxGroup>
					</FormItem>
					<Row>
						<Col span="12">
							<FormItem label="接待老人">
								<Switch v-model="serviceDemandObj.elder" size="large"><span slot="open">允许</span><span slot="close">禁止</span></Switch>
							</FormItem>
							<FormItem label="接待婴儿">
								<Switch v-model="serviceDemandObj.children" size="large"><span slot="open">允许</span><span slot="close">禁止</span></Switch>
							</FormItem>
							<FormItem label="接待海外">
								<Switch v-model="serviceDemandObj.abroad" size="large"><span slot="open">允许</span><span slot="close">禁止</span></Switch>
							</FormItem>
							<FormItem label="接待港澳台">
								<Switch v-model="serviceDemandObj.got" size="large"><span slot="open">允许</span><span slot="close">禁止</span></Switch>
							</FormItem>
						</Col>
						<Col span="12">
							<FormItem label="商业拍摄">
								<Switch v-model="serviceDemandObj.business" size="large"><span slot="open">允许</span><span slot="close">禁止</span></Switch>
							</FormItem>
							<FormItem label="带宠物">
								<Switch v-model="serviceDemandObj.pet" size="large"><span slot="open">允许</span><span slot="close">禁止</span></Switch>
							</FormItem>
							<FormItem label="吸烟">
								<Switch v-model="serviceDemandObj.smoke" size="large"><span slot="open">允许</span><span slot="close">禁止</span></Switch>
							</FormItem>
							<FormItem label="聚会">
								<Switch v-model="serviceDemandObj.party" size="large"><span slot="open">允许</span><span slot="close">禁止</span></Switch>
							</FormItem>
						</Col>
					</Row>
				</div>

				<FormItem label="交通">
					<Input class="view-input" :max="64" placeholder="多个请用空格分隔" v-model="formData.sojournEntity.trafficLabel" />
				</FormItem>
				<FormItem label="景点">
					<Input class="view-input" :max="64" placeholder="多个请用空格分隔" v-model="formData.sojournEntity.scenicSpot" />
				</FormItem>
				<FormItem label="美食">
					<Input class="view-input" :max="64" placeholder="多个请用空格分隔" v-model="formData.sojournEntity.deliciousFood" />
				</FormItem>

				<h1>规格信息</h1>
				<FormItem label="商品规格">
					<div style="border: 1px solid #cfcfcf;">
						<div style="padding: 8px" v-for="(item, index) in skuSpecList" :key="index">
							<FormItem label="规格属性" :label-width="80" style="margin-bottom:5px">
								<Select style="width: 150px;" v-model="skuSpecList[index].title" filterable allow-create @on-create="HandleCreate" @on-change="OnChangeSpec">
									<Option v-for="(specitem,id) in specNameOption" :value="specitem" :key="id">{{ specitem }}</Option>
								</Select>
								<Button @click="DelSpec(index)" style="margin-left:5px">删除</Button>
							</FormItem>
							<FormItem label="属性内容" :label-width="80">
								<div :class="{'spec-item':true}" v-for="(val, n) in skuSpecList[index].values" :key="n">
									<img v-if="n !== 0" @click="DelSpecValue(index,n)" class="del-spec" src="../../../images/ico-del.svg"/>
									<Input v-model="skuSpecList[index].values[n].specValue" @on-change="OnChangeSpecValue" placeholder="请输入SKU属性" style="margin-right: 0.5rem;width:150px" />
								</div>
								<a @click="AddSpecValue(skuSpecList[index].values)">添加属性</a>
							</FormItem>
						</div>
						<div class="button-addSpec">
							<Button @click="AddSpec">添加商品规格</Button>
						</div>
					</div>
				</FormItem>
				<FormItem label="规格明细">
					<Table border stripe :columns="sepcColumns" :data="formData.skuList"></Table>
				</FormItem>
				<template>
					<article id="editorContainer" style="margin-top:30px;margin-left:140px"></article>
				</template>
				<FormItem style="position:fixed;z-index:999999;bottom: 10px;right:50px">
						<Button type="primary" @click="Submit">保存</Button>
				</FormItem>
			</Form>
		</Content>
		<Modal title="View Image" v-model="visible">
			<img :src="imgName" v-if="visible" style="width: 100%">
		</Modal>
	</div>
</template>
<script>
import {SkuAlgorithm} from '@/libs/Algorithm'
import specNameDemo from '@/static/specNameDemo'
import E from '@/libs/SourceCodeEditor'
export default {
	name: 'GoodsCreate',
	props: {
		callbank: Function,
    seletions: Array
	},
	data() {
		return {
			basicLabels: ['无线网络','挂式空调','晾衣架','免费瓶装水','低楼层无电梯','窗户','电视','冰箱','洗衣机'],
			serviceLabels: ['免费停车位','行李寄存','前台服务'],
			bathroomLabels: ['热水','独立卫浴','电吹风','洗浴用品','牙具','浴巾','毛巾','干湿分离','免费洗衣服'],
			locationArounds: [],
			serviceDemandObj: {
				children: false,
				abroad: false,
				got: false,
				business: true,
				pet: false,
				smoke: false,
				party: false,
				elder: true
			},
			regionArray: [],
			spuFileViewAd: [],
			specFileView: [],
			orgFreeze: this.$store.getUser('userType') !== 9,
			skuImageUpload: [],
			uploadApi: `${env_config.upload_config.api}/agrobiz-file/v1.0/upload/single/file/binary`,
			uploadHeader: {
				'Authorization': 'Bearer ' + this.$store.getToken()
			},
			uploadParam: {
				catalog:'goods'
			},
			specNameOption: localStorage.getItem('specNameOption')?JSON.parse(localStorage.getItem('specNameOption')):specNameDemo,
			skuSpecList: [],
			sepcColumns: [],
			formData: {
				orgId: this.$store.getOrg('orgId'),
				shopId: this.$store.getShop('shopId'),
				shopName: this.$store.getShop('shopName'),
				salesModel: this.$store.getShop('shopType'),
				storeId: this.$store.getWms('warehouseId'),
				warehouseName: this.$store.getWms('warehouseName'),
				regionCode: this.$store.getWms('countyCode'),
				outputRate: 0,
				inputRate: 0,
				wholesalePrice: 0.00,
				profitRate: 0,
				spuImage: null,
				spuName: null, //商品名称
				categoryId: null, //类目id
				shopCategoryId: null,//店铺商品分类ID
				spuType: 10, //商品类型：10旅居商品
				groupId: null,
				miniBuy: 1, //多少件起售
				spuSort: 9,//排序
				spuArticle: null,
				skuList: [],
				sojournEntity: {
					bookingMode: 0
				}
			},
			imgName: null,
			visible: false,
			spuUploadList: [],
			spuUploadListAd: [],
			categoryArray: [],
			categoryList: [],
			shopCategoryList: [],
			editor: null,
			isGoods: true,
			defaultColumn: [
				{
					title: '客房图片',
					key: "skuImage",
					width:120,
					fixed: 'left',
					render: (h, params) => {
						return h('Upload',{
							props: {
								'on-success':(value,file)=> {
									this.skuSuccess(h,params.index, value)
								},
								headers:this.uploadHeader,
								data:this.uploadParam,
								action:this.uploadApi,
								type:"drag",
								showUploadList: false,
								name:"binaryFile"
							},
							style: {margin:'2px'}
						},this.skuImageUpload[params.index]?this.skuImageUpload[params.index]:this.defaultSkuImage(h,params.index))
					}
				},
				{
					title: '预订模式',
					key: "bookingMode",
					width: 180,
					render: (h, params) => {
						return h('Select', {
							props: {
								transfer:true,
								value: this.formData.skuList[params.index].bookingMode
							},
							on: {
								'on-change': (val) => {
									if(val){
										this.formData.skuList[params.index].bookingMode = val
									} else {
										this.formData.skuList[params.index].bookingMode = 0
									}
								}
							}
						},[h('Option', {props:{value: 0}}, '日租模式'),h('Option', {props:{value: 1}}, '长租模式'),h('Option', {props:{value: 2}}, '套餐模式')])
					}
				},
				{
					title: '联系电话',
					key: "contactMobile",
					width: 180,
					render: (h, params) => {
						return h('Input', {
							props: {
								value: this.formData.skuList[params.index].contactMobile,
								size: 'small'
							},
							on: {
								input: (val) => {
									if(val){
										this.formData.skuList[params.index].contactMobile = val
									} else {
										this.formData.skuList[params.index].contactMobile = '1'
									}
								}
							}
						})
					}
				},
				{
					title: '规格天数',
					key: "inventory",
					width:120,
					render: (h, params) => {
						return h('InputNumber', {
							props: {
								value: this.formData.skuList[params.index].taocanDay,
								size: 'small',
								min: 1
							},
							on: {
								input: (val) => {
									if(val){
										this.formData.skuList[params.index].taocanDay = Number(val)
									} else {
										this.formData.skuList[params.index].taocanDay = 1
									}
								}
							}
						})
					}
				},
				{
					title: '库存',
					key: "inventory",
					width:120,
					render: (h, params) => {
						return h('InputNumber', {
							props: {
								value: this.formData.skuList[params.index].inventory,
								size: 'small',
								min: 1
							},
							on: {
								input: (val) => {
									if(val){
										this.formData.skuList[params.index].inventory = Number(val)
									} else {
										this.formData.skuList[params.index].inventory = 0
									}
								}
							}
						})
					}
				},
				{
					title: '成本价(元)',
					key: "systemPrice",
					width:120,
					render: (h, params) => {
						return h('InputNumber', {
							props: {
								value: 0,
								size: 'small',
								min: 0
							},
							on: {
								input: (val) => {
									if(val){
										this.formData.skuList[params.index].systemPrice = parseFloat(val)
									} else {
										this.formData.skuList[params.index].systemPrice = 0
									}
								}
							}
						})
					}
				},
				{
					title: '零售价(元)',
					key: "salesPrice",
					width:120,
					render: (h, params) => {
						return h('InputNumber', {
							props: {
								value: 0,
								size: 'small',
								min: 0
							},
							on: {
								input: (val) => {
									if(val){
										this.formData.skuList[params.index].salesPrice = parseFloat(val)
									} else {
										this.formData.skuList[params.index].salesPrice = 0
									}
								}
							}
						})
					}
				},
				{
					title: '市场价(元)',
					key: "aroundPrice",
					width:120,
					render: (h, params) => {
						return h('InputNumber', {
							props: {
								value: 0,
								size: 'small',
								min: 0
							},
							on: {
								input: (val) => {
									if(val){
										this.formData.skuList[params.index].aroundPrice = parseFloat(val)
									} else {
										this.formData.skuList[params.index].aroundPrice = 0
									}
								}
							}
						})
					}
				},
				{
					title: '分销价(元)',
					key: "wholesalePrice",
					width:120,
					render: (h, params) => {
						return h('InputNumber', {
							props: {
								value: 0,
								size: 'small',
								min: 0
							},
							on: {
								input: (val) => {
									if(val){
										this.formData.skuList[params.index].wholesalePrice = parseFloat(val)
									} else {
										this.formData.skuList[params.index].wholesalePrice = 0
									}
								}
							}
						})
					}
				},
				{
					title: '计价单位',
					key: "skuUom",
					width:120,
					render: (h, params) => {
						return h('Input', {
							props: {
								value: this.formData.skuList[params.index].skuUom,
								size: 'small'
							},
							on: {
								input: (val) => {
									this.formData.skuList[params.index].skuUom = val
								}
							}
						})
					}
				}, 
				{
					title: '商品排序',
					key: "sortIndex",
					width:120,
					render: (h, params) => {
						return h('InputNumber', {
							props: {
								value: this.formData.skuList[params.index].sortIndex ? this.formData.skuList[params.index].sortIndex : 99,
								size: 'small'
							},
							on: {
								input: (val) => {
									if(val){
										this.formData.skuList[params.index].sortIndex = Number(val)
									} else {
										this.formData.skuList[params.index].sortIndex = 99
									}
								}
							}
						})
					}
				}
			]
		}
	},
	watch: {
		categoryArray(val) {
			if(val.length > 1) {
				let index = val.length - 1
				this.formData.categoryId = val[index]
				this.formData.categoryPath = val.slice(0,-1).join('/')
			} else {
				this.formData.categoryId = val[0]
				this.formData.categoryPath = '/'
			}
		},
		/* selectSpuType(val){
			if(val === 2) {
				this.isGoods = false
				this.defaultColumn.forEach((element,id) => {
					if(['skuWeight','skuNo'].indexOf(element.key) > -1) {
						this.defaultColumn.splice(id,1)
					}
				})
			} else {
				this.isGoods = true
			}
		} */
	},
	computed: {
		/* selectSpuType(){
			return this.formData.spuType
		} */
	},
	methods: {
		getCategoryList(){
			new this.$rest({
				gateway: 'agroerp',
				service: 'agroerp-shop',
				url: '/v1.0/plus/category/lazy',
				query: {
					equal:{
						categoryType: 0
					}
				},
				action: (res)=>{
					if(res.data.code === 20000){
						const data = res.data.data
						this.categoryList = data
					} else {
						this.$Notice.warning({
							title: '商品分类获取失败',
							desc: `失败原因：${res.data.msg}`
						})
					}
				}
			}).get()
		},
		getShopCategory(){
			new this.$rest({
				gateway: 'agroerp',
				service: 'agroerp-shop',
				url: '/v1.0/shop/category/page',
				query: {
					equal:{
						shopId: this.$store.getShop('shopId')
					},
					pageIndex: 1,
					pageSize: 21
				},
				action: (res)=>{
					if(res.data.code === 20000){
						const data = res.data.data.list
						this.shopCategoryList = data
					} else {
						this.$Notice.warning({
							title: '店铺商品分类获取失败',
							desc: `失败原因：${res.data.msg}`
						})
					}
				}
			}).get()
		},
		loadData (item, callback) {
			item.loading = true;
			new this.$rest({
				service: 'agroerp-shop',
				gateway: 'agroerp',
				url: '/v1.0/plus/category/lazy',
				query: {
					equal: {
						categoryPid: item.value,
						categoryType: 0
					},
				},
				action: (res)=>{
					if(res.data.code === 20000){
						const data = res.data.data
						item.children = data
						item.loading = false;
                    callback();
					} else {
						this.$Notice.warning({
							title: '商品分组获取失败2',
							desc: `失败原因：${res.data.msg}`
						})
					}
				}
			}).get()
		},
		Init(){
			this.getCategoryList()
			this.getShopCategory()
		},
		HandleCreate(val){
			this.specNameOption.unshift(val)
			localStorage.setItem('specNameOption',JSON.stringify(this.specNameOption))
		},
		//添加规格
		AddSpec() {
			const uid = new Date().getTime()
			const spec = {
				title: null,
				key: "specValue",
				values: [{
					specValue: null,
					specImg: null,
					uid: uid
				}]
			}
			this.skuSpecList.push(spec)
			if(this.skuSpecList.length === 1) {
				this.$nextTick(()=>{
					if(this.$refs[uid]) this.skuSpecList[0].values[0].ivu = this.$refs[uid][0].fileList
				})
			}
		},
		//修改规格
		OnChangeSpec() {
			const sku = new SkuAlgorithm().build(this.formData.spuName, this.skuSpecList)
			let columnLeft = sku.getColumns()
			columnLeft.push.apply(columnLeft, this.defaultColumn)
			this.sepcColumns = columnLeft
		},
		//删除规格
		DelSpec(index) {
			this.skuSpecList.splice(index, 1)
			this.OnChangeSpecValue()
		},
		//添加属性
		AddSpecValue(spec) {
			const uid = new Date().getTime()
			spec.push({
				specValue: null,
				specImg: null,
				uid: uid
			})
			this.$nextTick(()=>{
				if(this.$refs[uid])
					spec[spec.length-1].ivu = this.$refs[uid][0].fileList
			})
		},
		//修改属性
		OnChangeSpecValue() {
			const sku = new SkuAlgorithm().build(this.formData.spuName, this.skuSpecList)
			let columnLeft = sku.getColumns()
			columnLeft.push.apply(columnLeft, this.defaultColumn)
			this.sepcColumns = columnLeft
			//合并两个数组对象
			if(this.formData.skuList.length > sku.getSkuList().length) {
				this.formData.skuList.length = sku.getSkuList().length
			}
			sku.getSkuList().forEach((element,index) => {
				if(this.formData.skuList[index]) {
					Object.assign(this.formData.skuList[index],element)
				} else {
					this.formData.skuList.push(element)
				}
				//自动填充SPU图片做为SKU默认图片，避免重复上传，提交表单保存会用
				if(this.spuUploadList[0] && this.spuUploadList[0].src) {
					this.formData.skuList[index].skuImage = this.spuUploadList[0].src
				}
			})
			console.log('formData -> ',this.formData)
		},
		//删除属性
		DelSpecValue(index,n){
			this.skuSpecList[index].values.splice(n, 1)
			this.OnChangeSpecValue()
		},
		handleView(src) {
			this.$Modal.info({
				content: `<img style="width:100%" src="${src}">`,
				width: '500px',
			})
		},
		handleRemove(id) {
			this.spuUploadList.splice(id, 1)
		},
		handleFormatError(file) {
			this.$Notice.warning({
				title: '图片格式不支持',
				desc: `${file.name}图片格式不支持，请使用jpg、jpeg、png`
			})
		},
		handleMaxSize(file) {
			this.$Notice.warning({
				title: '图片过大',
				desc: `${file.name}图片大小不能超过2M`
			})
		},
		onUploadSuccess(response, file, fileList) {
			if(response.code == 20000){
				fileList.forEach(element => {
					element.src = element.response.data.protocol + element.response.data.hostName + element.response.data.filePath
				})
			} else {
				this.$Notice.warning({
					title: '上传失败',
					desc: `失败原因：${response.msg}`
				})
			}
			console.log('spuUploadList ->',this.spuUploadList)
		},
		skuSuccess(h,index,value) {
			this.formData.skuList[index].skuImage = value.data.protocol + value.data.hostName + value.data.filePath
			this.$set(this.skuImageUpload,index,[h('img',{attrs: {src: value.data.protocol+value.data.hostName +value.data.filePath},style: {width: "50px",verticalAlign: "middle",margin:"3px"}},'view')])
		},
		defaultSkuImage(h,index) {
			if(this.spuUploadList[0] && this.spuUploadList[0].src) {
				//自动填充SPU图片做为SKU默认图片，避免重复上传，展示用
				this.formData.skuList[index].skuImage = this.spuUploadList[0].src
				this.$set(this.skuImageUpload,index,[h('img',{attrs: {src: this.spuUploadList[0].src},style: {width: "50px",verticalAlign: "middle",margin:"3px"}},'view')])
				return null
			} else {
				return '点击上传'
			}
		},
		handleSuccess(response, file, fileList) {
			if(response.code === 20000){
				file.src = response.data.url
			} else {
				this.$Notice.warning({
					title: '上传失败',
					desc: `失败原因：${response.msg}`
				})
			}
		},
		spuHandleBeforeUpload(file) {
			window.URL = window.URL || window.webkitURL
			const check = this.spuUploadList.length < 5
			if (!check) {
				this.$Notice.warning({
					title: '最多可上传5张商品图'
				})
			}
			return check
		},
		spuHandleBeforeUploadAd(file) {
			window.URL = window.URL || window.webkitURL
			const check = this.spuUploadListAd.length < 1
			if (check) {
				this.spuFileViewAd.push(window.URL.createObjectURL(file))
			} else {
				this.$Notice.warning({
					title: '最多可上传1张商品图'
				})
			}
			return check
		},
		Submit() {
			if(this.spuUploadList.length === 0) {
				this.$Notice.warning({
					title: '必填项为空',
					desc: `请上传商品图`
				})
				return false
			}
			if(this.formData.skuList.length === 0) {
				this.$Notice.warning({
					title: '必填项为空',
					desc: `请添加商品规格`
				})
				return false
			}
			if(!this.formData.sojournEntity.roomNumber) {
				this.$Notice.warning({
					title: '客房编号必填',
					desc: `请输入客房编号，不同客房编号唯一`
				})
				return false
			}
			this.seletions.forEach(element => {
				if(this.formData.orgId === element.orgId) {
					this.formData.orgName = element.orgName
				}
			})
			this.formData.spuImage = this.spuUploadList[0].src
			this.formData.spuArticle = this.editor.txt.html()
	
			this.formData.skuList.forEach(item => {
				item.skuModel = ''
				item.specEntityList.forEach(element => {
					item.skuModel += element.specValue + ','
				})
				item.skuModel = item.skuModel.substring(0,item.skuModel.length-1)
			})

			let goodsAlbum = []
			this.spuUploadList.forEach(element => {
				let album = new Object()
				album.src = element.src
				album.type = 0
				goodsAlbum.push(album)
			})
			this.formData.goodsAlbum = JSON.stringify(goodsAlbum)
			this.formData.sojournEntity.serviceDemand = JSON.stringify(this.serviceDemandObj)
			this.formData.sojournEntity.basicLabel = this.basicLabels.join(' ')
			this.formData.sojournEntity.serviceLabel = this.serviceLabels.join(' ')
			this.formData.sojournEntity.bathroomLabel = this.bathroomLabels.join(' ')
			this.formData.sojournEntity.locationAround = this.locationArounds.join(' ')
			
			new this.$rest({
				gateway: 'agroerp',
				service: "agroerp-shop",
				url: '/v1.0/agromall/create/basic/sku',
				data: {
					pojo: this.formData,
				},
				action: (res) => {
					if (res.data.code === 20000) {
						this.callbank()
					} else {
						this.$Notice.warning({
							title: "操作失败",
							desc: `失败原因：${res.data.msg}`
						})
					}
				}
			}).post()
		},
		initEditor() {
			this.editor = new E('#editorContainer')
			this.editor.config.height = 800
			this.editor.config.placeholder = '商品详情介绍'
			this.editor.config.uploadImgServer = `${env_config.upload_config.api}/agrobiz-file/v1.0/upload/single/file/binary`
			this.editor.config.uploadImgMaxSize = 1 * 1024 * 1024
			this.editor.config.uploadImgMaxLength = 1
			this.editor.config.uploadFileName = 'binaryFile'
			this.editor.config.uploadImgParams = {
				catalog:'goods',
				selfName: false
			}
			this.editor.config.uploadImgHeaders = {
				'Authorization': 'Bearer ' + this.$store.getToken()
			}
			this.editor.config.uploadImgHooks = {
				success: (xhr)=>{
					console.log('图片插入成功',xhr)
				},
				fail: (xhr, editor, resData)=>{
					console.log('fail', resData)
					this.$Message.error('图片插入时出错')
				},
				error: (xhr, editor, resData)=>{
					console.log('error', xhr, resData)
					this.$Message.error('http请求异常')
				},
				timeout: (xhr)=>{
					console.log('timeout')
					this.$Message.error('上传超时')
				},
				customInsert: (insertImgFn, result)=>{
					console.log('result ->',result)
					if(result.code === 20000){
						insertImgFn(result.data.protocol + result.data.hostName+ result.data.filePath)
					} else {
						this.$Notice.error({
							title: '上传失败',
							desc: `原因：${result.msg}`
						})
					}
				}
			}
			this.editor.create()
		}
	},
	created(){
		
	},
	mounted() {
		this.spuUploadList = this.$refs.spu_upload.fileList;
		// this.spuUploadListAd = this.$refs.broad_upload.fileList;

		//初始化富文本编辑器
		this.initEditor()
	},
	beforeUnmount() {
		this.editor.destroy()
	}
}
</script>
<style lang="less" scoped>
table{
	th {
    border: 1px solid #ccc;
    min-width: 50px;
    height: 20px;
        background-color: yellow;
    }
}

h1 {
	background-color: #f5f5f5; font-size: 18px;
	padding: 10px;
	color: #333;
	margin-bottom: 18px;
}

.vertical-center-modal {
	display: flex;
	align-items: center;
	justify-content: center;
}

.demo-upload-list {
	display: inline-block;
	width: 60px;
	height: 60px;
	background: #fff;
	position: relative;
	margin-right: 4px;
}

.demo-upload-list img {
	width: 100%;
	height: 100%;
	border-radius: 4px;
	box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
}

.demo-upload-list-cover {
	display: none;
	position: absolute;
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;
	background: rgba(0, 0, 0, .6);
}

.demo-upload-list:hover .demo-upload-list-cover {
	display: block;
}

.demo-upload-list-cover i {
	color: #fff;
	font-size: 20px;
	cursor: pointer;
	margin: 0 2px;
}

.intro-con {
	min-height: 140px;
}

.draggable-btn {
	margin-top: 20px;
}

.code-con {
	width: 400px;
	background: #F9F9F9;
	padding-top: 10px;
}

.goods-type div.box-in {
	border: 1px solid #d9c9c6;
	text-align: center;
	cursor: pointer;
	height: 60px;
	position: relative;
}

.goods-type div.box-in>img {
	width: 25%;
	height: 50%;
	position: absolute;
	bottom: 0;
	right: 0;
}

.view-input {
	width: 50%;
}

.category-params {
	background-color: #f5f5f5;
	padding: 10px;
}

.button-addSpec {
	width: 98%;
	background-color: #f5f5f5;
	margin: 10px auto;
	padding: 8px;
}
.spec-item {
	display: inline-block; vertical-align: top; position: relative;
}
.have-img {
	height: 110px;
}
.spec-item:hover .del-spec {
	display: block;
}
.spec-item .del-spec {
	position: absolute; top: -8px; right: 0; width: 20px; z-index: 99; opacity: .5; display: none; cursor: pointer;
}
.spec-item .ivu-upload {
	position: absolute; top: 40px; left: 22px;
}
.spec-img {
	margin-top: 5px;
}
.spec-img>img {
	width: 100px; height: 80px; border-radius: 5px; border: 2px solid #FFFFFF;
}
.spec-img>img:hover {
	box-shadow: 0 0 7px #00000050;
}
footer {
	position: fixed; width: auto; bottom: 25px; left: 200px; right: 0; text-align: center; z-index: 999999;
}

th .ivu-table-cell {
	white-space: nowrap;
}
.ivu-table-cell {
	white-space: nowrap;
}
.skuTab b {
	padding: 0 10px; cursor: pointer;
}

.sojourn-goods {
	position: absolute; top: 80px; right: 30px; width: 600px; z-index: 10;
	background: #f3f3f3ba; border: 1px solid #dcdee2; border-radius: 4px; padding: 10px;
}
.ivu-checkbox-group-item, .ivu-switch {
	color: gray;
}
</style>
